<script setup lang="ts">
import {ref} from 'vue';
import myAxios from '../plugins/myAxios.ts';
import UserCardList from '../components/UserCardList.vue';
import {UserType} from "../models/user";

const currentPage = ref(0);
const userList = ref<UserType[]>([]);
const listLoading = ref(false);
const finished = ref(false);
const refreshLoading = ref(false);

const fetchUsers = async (currentPage: number): Promise<void> => {
  try {
    console.log("currentPage",currentPage)
    const userRes = await myAxios.get('/user/recommend', {
      params: {
        current: currentPage,
        size: 5,
      },
    });

    if (userRes.code === 0) {
      if (!userRes.data || !userRes.data.records || userRes.data.records.length === 0) {
        finished.value = true;
        return;
      }

      const userDataList = userRes.data.records.map(user => {
        if (user.userTags) {
          user.userTags = JSON.parse(user.userTags);
        }
        return user;
      });

      userList.value = [...userList.value, ...userDataList];
    } else {
      // 处理非成功状态码的情况，例如提示用户错误信息或重置状态
      console.error('Request failed with code:', userRes.code);
      finished.value = true; // 或者根据实际情况决定是否设置为true
    }
  } catch (error) {
    console.error('Error fetching data:', error);
    // 在这里也可以根据错误类型决定是否结束加载
    finished.value = true;
  } finally {
    listLoading.value = false;
  }
};

const onLoad = async () => {
  if (!finished.value) {
    listLoading.value = true;
    currentPage.value  = currentPage.value + 1;
    await fetchUsers(currentPage.value);
  }
};

const onRefresh = async () => {
  currentPage.value = 1;
  userList.value = [];
  await fetchUsers(currentPage.value);
  refreshLoading.value = false;
  listLoading.value = false;
};
</script>

<template>
  <van-pull-refresh v-model="refreshLoading" @refresh="onRefresh">
    <van-list
        v-model:loading="listLoading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
    >
      <van-cell v-for="user in userList" :key="user.id">
        <UserCardList :user="user"/>
      </van-cell>
    </van-list>
  </van-pull-refresh>
</template>

<style scoped>/* Your styles here */
</style>